import json
import sys

import facade
import pymysql
from xjlibrary.our_file_dir import BaseDir

curPath = BaseDir.get_file_dir_absolute(__file__)
configfile = BaseDir.get_new_path(curPath, "db.ini")


class DownJournal(object):
    def __init__(self):
        self.logger = facade.get_streamlogger()
        self.mysqlutil = facade.MysqlUtiles(configfile, "db", logger=self.logger)
        self.header = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Host": "user.bookan.com.cn",
            "Pragma": "no-cache",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
        }
        self.yeardicts = {}

    def down_year(self, jid):
        """
        获取年
        :return:
        """
        url = "http://user.bookan.com.cn/index.php?op=Resource.pastYearList&resourceType=1&resourceId={}".format(jid)
        BoolResult, errString, r = facade.BaseRequest(url,
                                                      endstring="",
                                                      headers=self.header,
                                                      timeout=(30, 60),
                                                      mark="status")
        if BoolResult:
            jsondicts = json.loads(r.text)
            datajson = jsondicts["data"]
            for onedata in datajson:
                year = onedata["year"]
                count = onedata["count"]
                self.yeardicts[year] = count
        else:
            print("下载年份失败")
            sys.exit(-1)

    def down_one_year(self, jid, year, subjid):
        """
        获取每一年的期
        :return:
        """
        count = self.yeardicts[year]
        url = "http://user.bookan.com.cn/index.php?op=Resource.yearList&resourceType=1&resourceId={}&year={}&month=0&pageNum=1&limitNum={}".format(
            jid, year, count)
        BoolResult, errString, r = facade.BaseRequest(url,
                                                      endstring="",
                                                      headers=self.header,
                                                      timeout=(30, 60)
                                                      )
        if BoolResult:
            jsondicts = json.loads(r.text)
            data = jsondicts["data"]
            for onedata in data:
                issueId = onedata["issueId"]
                issueName = pymysql.escape_string(onedata["issueName"])
                resourceId = onedata["resourceId"]
                jpg = onedata["jpg"]
                imageurl = "http://img1-qn.bookan.com.cn/page{jpg}/{id}/{id}-{issueId}/cover_small.mg".format(jpg=jpg,
                                                                                                              id=resourceId,
                                                                                                              issueId=issueId)
                sql = "insert ignore into issue(issueid,issuename,resourceId,subjid,cover) values ('%s','%s','%s','%s','%s')"
                sql = sql % (issueId, issueName, resourceId, subjid, imageurl)
                self.mysqlutil.ExeSqlToDB(sql)

    def task(self):
        sql = "select jid,subjid from journal where stat = 0 order by RAND() limit 100"
        rows = self.mysqlutil.SelectFromDB(sql)
        if rows:
            for row in rows:
                jid = row[0]
                self.down_year(jid)
                for year in self.yeardicts:
                    self.down_one_year(jid, year, row[1])
                sql = "update journal set stat=1 where jid='{}'".format(jid)
                self.mysqlutil.ExeSqlToDB(sql)
        else:
            return "break"


def main():
    down = DownJournal()
    while True:
        results = down.task()
        if results == "break":
            break


if __name__ == "__main__":
    main()
